import net.iasolution.vendingmachine.constance.*
import vendingmachine.*
import grails.converters.JSON
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class BootStrap {

    def init = { servletContext ->
		if(ShiroUser.count()==0 || ShiroRole.count()==0){
			new ShiroRole(name:VendingConstance.ROLE_ADMIN).save()
			new ShiroRole(name:VendingConstance.ROLE_USER).save()
			new ShiroUser(username:'admin',
				          passwordHash: "admin".encodeAsSHA256(),
						  email: "admin@gmail.com",
						  cardId: "x",
						  facebookId: "x",
						  gender: "x",
						  authToken: "x"
						  ).addToRoles(ShiroRole.findByName("admin")).save()
		   new ShiroUser(username:'default',
							  passwordHash: "default".encodeAsSHA256(),
							  email: "default@gmail.com",
							  cardId: "x",
							  facebookId: "default",
							  gender: "x",
							  authToken: "x"
							  ).addToRoles(ShiroRole.findByName("admin")).save()
							  
		}
		if(MatchState.count()==0){
			new MatchState(name:VendingConstance.MATCH_STATE_UN_USE).save()
			new MatchState(name:VendingConstance.MATCH_STATE_USED).save()
		}
		if(Coupon.count()==0){
			new Coupon(item:"e-coupon from iasolution",description:"it's a test coupon").save()
		}
		
		// initial the token that's sync with dews 
		
		SynccsJob.setToken(requestTokenWithDEWS())
    }
	private String requestTokenWithDEWS(){
		
		
		def urlString = ConfigurationHolder.config.dews.token.url + 
					    "?grant_type=client_credentials"+
		                "&client_id="+ ConfigurationHolder.config.dews.token.client +
						"&client_secret=" + ConfigurationHolder.config.dews.token.secret
		println "urlString = ${urlString}"
		def url = new URL(urlString)
		def conn = url.openConnection()
		conn.setRequestMethod("GET")
		conn.setRequestProperty("Accept","application/json")
		conn.doOutput = true
		conn.connect()
		return parseToken(conn.content.text)
	}
	/**
	 * format : 
{
    "access_token": "601ea143-5d69-4a11-9dc5-a8df3ca73cf4",
    "expires_in": 43199,
    "refresh_token": "9c00bcb9-d850-4dc8-8598-0262f110dfea",
    "token_type": "bearer"
}
	 * */
	private String parseToken(def text){
		def json = JSON.parse(text)
		println "parseToken : ${json.access_token}"
		return json.access_token
	}
    def destroy = {
    }
}
